package com.nanuminc.market.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.util.Log;

class HttpPostDataTrans {
	StringBuilder builder;
	String result;
	String boundary = "*****";
	String twoHyphens = "--";
	String lineEnd = "\r\n";
	FileInputStream mFileInputStream;
	File sendFile;
	
	/*********************************************************
	 * 사진이 포함 된 글 등록
	 *********************************************************/
	public void postDataTrans(String cmdPath, String nickname, String email, String authKey, 
			String latitude, String longitude, String fileName, String comment, String infotype, String currentAddr) {
		
		try {

			if(fileName != null)
				mFileInputStream = new FileInputStream(fileName);	
			
			URL url = new URL(cmdPath); 
			HttpURLConnection http = (HttpURLConnection) url.openConnection();   
				                                           
			http.setDoInput(true);
			http.setDoOutput(true);
			http.setUseCaches(false);
			http.setConnectTimeout(10000); // Timeout
			http.setRequestMethod("POST");
			http.addRequestProperty("Connection", "Keep-Alive");  //Test Server
			http.setRequestProperty("content-type", "multipart/form-data;boundary=" + boundary);     // Test Server  
			
			DataOutputStream dos = new DataOutputStream(http.getOutputStream());
		
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"contents"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(URLEncoder.encode(comment, "UTF-8"));
			dos.writeBytes(lineEnd);

			Log.e("hyup2","typeposition : "+infotype);
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"infoTypeCode"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(infotype);
			dos.writeBytes(lineEnd);
			
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"localInfo"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(URLEncoder.encode(currentAddr, "UTF-8"));
			dos.writeBytes(lineEnd);

			Log.e("hyup2","upload authKey = "+authKey);
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"authKey"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(authKey); // hyup2 
			dos.writeBytes(lineEnd);
			
			if(latitude!=null && longitude!=null)
			{
				dos.writeBytes(twoHyphens+boundary+lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\""+"latitude"+"\""+ lineEnd);
				dos.writeBytes(lineEnd);
				dos.writeBytes(latitude);  
				dos.writeBytes(lineEnd);
				
				dos.writeBytes(twoHyphens+boundary+lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\""+"longitude"+"\""+ lineEnd);
				dos.writeBytes(lineEnd);
				dos.writeBytes(longitude); 
				dos.writeBytes(lineEnd);
			}
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"nickName"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(URLEncoder.encode(nickname, "UTF-8")); 
			dos.writeBytes(lineEnd);
			
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"emailAddr"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(email); 
			dos.writeBytes(lineEnd);
			
			/*
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+"user_key"+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(user_key);
			dos.writeBytes(lineEnd);
			
			dos.writeBytes(twoHyphens+boundary+lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\""+userType+"\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(tokid);
			dos.writeBytes(lineEnd);
			*/
			if(fileName != null)
			{
				   // write data
				   dos.writeBytes(twoHyphens + boundary + lineEnd);
				   dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName+"\"" + lineEnd);
				   dos.writeBytes("Content-Type:image/jpeg"+lineEnd);
				   dos.writeBytes(lineEnd);
				   
				   int bytesAvailable = mFileInputStream.available();
				   int maxBufferSize = 1024;
				   int bufferSize = Math.min(bytesAvailable, maxBufferSize);
				   
				   byte[] buffer = new byte[bufferSize];
				   int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
				   
				   Log.e("hyup2", "image byte is " + bytesRead);
				   
				   // read image
				   while (bytesRead > 0) {
				    dos.write(buffer, 0, bufferSize);
				    bytesAvailable = mFileInputStream.available();
				    bufferSize = Math.min(bytesAvailable, maxBufferSize);
				    bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
				   } 
				   
				   dos.writeBytes(lineEnd);
				   

					mFileInputStream.close();
					dos.flush(); // finish upload...	
					Log.e("hyup2", "finish upload... ");
			}
			
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
			
			InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8"); 
			BufferedReader reader = new BufferedReader(tmp); 
			builder = new StringBuilder(); 
			String str; 
			
			while ((str = reader.readLine()) != null) {      
				builder.append(str);
			} 
			
			result = builder.toString();
			dos.close();
			tmp.close();
			reader.close();
			Log.e("hyup2", "result = "+result);
		} catch (MalformedURLException e) {
			
		} catch (IOException e) {
			
		}
	}
	
	
	/*********************************************************
	 * 정보 등록/수정
	 * 
	 * param     mode 		: 수정하려는 item
	 *               cmdPath	: API
	 *               authKey	: 인증키
	 *               emailAddr	: 이메일주소
	 *               fileName	: 파일이름  
	 *********************************************************/
	public void InfoEditTrans(String mode, String cmdPath, String authKey, String emailAddr, String memo){
		StringBuffer buffer = new StringBuffer();;
		
		buffer.append("authKey").append("=").append(authKey).append("&"); 
		buffer.append("emailAddr").append("=").append(emailAddr).append("&");
		if(mode.equals("NAME"))
			buffer.append("nickName").append("=").append(memo);
		else if(mode.equals("INTRO"))
			buffer.append("introduction").append("=").append(memo);
		else // 푸시설정
			buffer.append("alertCheck").append("=").append(memo);
		
		Log.d("hyup2","buffer = "+buffer.toString());
		Log.d("hyup2","cmdPath = "+cmdPath);

		try { 
			
			URL url = new URL(cmdPath); 
			HttpURLConnection http = (HttpURLConnection) url.openConnection();   
			
			http.setDefaultUseCaches(false);                                            
			http.setDoInput(true);                 
			http.setDoOutput(true);   
			http.setConnectTimeout(10000); // Timeout 
			http.setRequestMethod("POST");         
			
			http.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
          
			OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
			PrintWriter writer = new PrintWriter(outStream); 
			writer.write(buffer.toString()); 
			writer.flush(); 

			InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8"); 
			BufferedReader reader = new BufferedReader(tmp); 
			builder = new StringBuilder(); 
			String str; 
			while ((str = reader.readLine()) != null) {      
				builder.append(str);  
			} 
			tmp.close();
			reader.close();
			outStream.close();
			writer.close();
			
			Log.e("hyup2", "result = "+builder.toString());
			
		} catch (MalformedURLException e) {
			
		} catch (IOException e) {
			
		}
	 
  
	}
	
	/*********************************************************
	 * 프로필 사진 등록/수정
	 * 
	 * param     cmdPath	: API
	 *               authKey	: 인증키
	 *               emailAddr	: 이메일주소
	 *               fileName	: 파일이름  
	 *********************************************************/
	public void PhotoEditTrans(String cmdPath, String authKey, String emailAddr, String fileName){

			Log.d("hyup2","cmdPath : "+cmdPath);
			Log.d("hyup2","authKey : "+authKey);
			Log.d("hyup2","emailAddr : "+emailAddr);
			Log.d("hyup2","fileName : "+fileName);
			URL url;
			try {
				mFileInputStream = new FileInputStream(fileName);	
				
				url = new URL(cmdPath);
	
				HttpURLConnection http = (HttpURLConnection) url.openConnection();   
				Log.i("hyup2","000000000");                     
				http.setDoInput(true);
				http.setDoOutput(true);
				http.setUseCaches(false);
				http.setConnectTimeout(10000); // Timeout
				http.setRequestMethod("POST");
				http.addRequestProperty("Connection", "Keep-Alive");  //Test Server
				http.setRequestProperty("content-type", "multipart/form-data;boundary=" + boundary);     // Test Server  
				DataOutputStream dos = new DataOutputStream(http.getOutputStream());
			
				dos.writeBytes(twoHyphens+boundary+lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\""+"authKey"+"\""+ lineEnd);
				dos.writeBytes(lineEnd);
				dos.writeBytes(authKey);
				dos.writeBytes(lineEnd);
				
				dos.writeBytes(twoHyphens+boundary+lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\""+"emailAddr"+"\""+ lineEnd);
				dos.writeBytes(lineEnd);
				dos.writeBytes(emailAddr); // hyup2 
				dos.writeBytes(lineEnd);
				
				dos.writeBytes(twoHyphens + boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName+"\"" + lineEnd);
				dos.writeBytes("Content-Type:image/jpeg"+lineEnd);
				dos.writeBytes(lineEnd);
				
				int bytesAvailable = mFileInputStream.available();
				int maxBufferSize = 1024;
				int bufferSize = Math.min(bytesAvailable, maxBufferSize);
				
				byte[] buffer = new byte[bufferSize];
				int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
				   
				Log.e("hyup2", "image byte is " + bytesRead);
				   
				   // read image
				while (bytesRead > 0) {
				    dos.write(buffer, 0, bufferSize);
				    bytesAvailable = mFileInputStream.available();
				    bufferSize = Math.min(bytesAvailable, maxBufferSize);
				    bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
				} 
				   
				dos.writeBytes(lineEnd);
				   

				mFileInputStream.close();
				dos.flush(); // finish upload...	
				Log.e("hyup2", "finish upload... ");
				
				dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
				
				InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8"); 
				BufferedReader reader = new BufferedReader(tmp); 
				builder = new StringBuilder(); 
				String str; 
				
				while ((str = reader.readLine()) != null) {      
					builder.append(str);
				} 
				
				result = builder.toString();
				dos.close();
				tmp.close();
				reader.close();
				Log.e("hyup2", "result = "+result);
			} catch (Exception e) {

			} 
	}
}
